import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as fs from 'fs';
import * as path from 'path';
import * as yaml from 'js-yaml';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 配置 Swagger 文档
  const config = new DocumentBuilder()
    .setTitle('NestJS 工具箱 API')
    .setDescription('NestJS 工具箱 API 文档')
    .setVersion('1.0')
    .addTag('cloudinary', 'Cloudinary 图片处理服务')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document);

  // 导出 Swagger 文档为 JSON 文件
  const outputPath = path.resolve(process.cwd(), 'swagger-docs');
  if (!fs.existsSync(outputPath)) {
    fs.mkdirSync(outputPath, { recursive: true });
  }

  // 保存为 JSON 文件
  fs.writeFileSync(
    path.join(outputPath, 'swagger-spec.json'),
    JSON.stringify(document, null, 2),
    { encoding: 'utf8' },
  );

  // 保存为 YAML 文件
  fs.writeFileSync(
    path.join(outputPath, 'swagger-spec.yaml'),
    yaml.dump(document),
    { encoding: 'utf8' },
  );

  console.log(`Swagger 文档已导出到 ${outputPath} 目录`);

  await app.listen(process.env.PORT ?? 3000);
}

bootstrap().catch((err) => {
  console.error('启动应用失败:', err);
  process.exit(1);
});
